package com.example.myshools.Mine.student;

import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.myshools.Mine.student.edit.StudentData;
import com.example.myshools.R;
import com.example.myshools.entity.Constant;
import com.example.myshools.entity.Orgnaization;
import com.example.myshools.entity.Student;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class StudentFragment extends Fragment {
    private ImageView headImg;
    private ImageView isRenZ;//认证出现
    private ImageView inToJS;
    private TextView oName;
    private TextView oLevel;
    private TextView isRenZh;

    private LinearLayout myNews;
    private LinearLayout mySchoolFriend;
    private LinearLayout settings;
    private int role;
    private int id;
    private Orgnaization orgnaization = new Orgnaization();
    private Student student = new Student();
    private Gson gson = new Gson();
    private static String user_head_path = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View newView = inflater.inflate(R.layout.student_fragment, container, false);


        //根据id,查询个人信息
        //首先判断是组织还是个人
       //0是组织，1是个人，在登录的时候设置全局变量,获取用户id值
        role=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE).getInt("role",-1);
        id = 1;
        return newView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /* sharedPreferences=getContext().getSharedPreferences(String.valueOf(id), Context.MODE_PRIVATE);*/
        //EventBus.getDefault().register(this);
        headImg = getActivity().findViewById(R.id.o_head_img);
        oName = getActivity().findViewById(R.id.o_name);
        oLevel = getActivity().findViewById(R.id.o_level);
        isRenZ = getActivity().findViewById(R.id.is_ren_zheng);
        isRenZh = getActivity().findViewById(R.id.ren_zheng);
        inToJS = getActivity().findViewById(R.id.btn_into_xiangqing);
        myNews = getActivity().findViewById(R.id.my_news);
        mySchoolFriend = getActivity().findViewById(R.id.my_school_friend);
        settings = getActivity().findViewById(R.id.settings);
        getUserData();
        setAdapter();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //EventBus.getDefault().unregister(this);
    }
    private void setAdapter() {
        MyClickListener my = new MyClickListener();
        inToJS.setOnClickListener(my);
        myNews.setOnClickListener(my);
        mySchoolFriend.setOnClickListener(my);
        settings.setOnClickListener(my);
    }
    private void setView(int r) {
        Message message = new Message();
        message.what = 3;
        message.obj = r;
        handler.sendMessage(message);
            oName.setText(student.getStuNickName() + "");
            oLevel.setText(student.getStuNumber() + "");
            if (student.getIsIdentity() == 0) {
                isRenZ.setVisibility(View.GONE);
                isRenZh.setText("未认证");
            } else if (student.getIsIdentity() == 2) {
                isRenZ.setVisibility(View.GONE);
                isRenZh.setText("正在认证中");
            } else {
                isRenZh.setText("已认证");
                isRenZ.setVisibility(View.VISIBLE);
            }
    }
    //@Subscribe(threadMode = ThreadMode.ASYNC)
    public void getUserData() {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder().add("id", String.valueOf(id)).build();
        String url = Constant.url + "user/findStudentById";
        final Request request = new
                Request.Builder().url(url).post(body).build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("de===", "连接失败！！！！！！！");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("ss", string.toString());
                Message message = new Message();
                message.what = 1;
                message.obj = string;
                handler.sendMessage(message);
            }
        });
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.loading).error(R.drawable.headfail).fallback(R.drawable.loading).diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop();
            if (msg.what == 1) {
                Gson gson = new GsonBuilder().serializeNulls().create();
                    student = gson.fromJson(msg.obj.toString(), Student.class);
                    if (user_head_path == null &&student.getHeadPath()!=null) {
                        user_head_path = student.getHeadPath();
                        Glide.with(getContext()).load(orgnaization.getHeadPath()).apply(requestOptions).into(headImg);
                    }
                setView(role);
            }
            if (msg.what == 3) {
                    if(user_head_path!=null&&user_head_path!=student.getHeadPath()) {//说明头像更改，重新加载
                        Glide.with(getContext()).load(student.getHeadPath()).apply(requestOptions).into(headImg);
                    }//否则不做改
            }
            if (msg.what == 10) {
                getUserData();
                setAdapter();
            }


        }
    };

    private class MyClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.btn_into_xiangqing:
                        Intent intent = new Intent(getActivity(), StudentData.class).putExtra("s", gson.toJson(student));
                        startActivity(intent);
                        break;
            }

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume", "onResum");
        Message message = new Message();
        message.what = 10;
        handler.sendMessage(message);
    }

}

